<template>
  <div class="body">
    <div class="login-box">
      <h3 style="color: royalblue">商家登陆</h3>
      <el-form :model="loginForm" :rules="rules" ref="loginForm" label-width="100px">
        <el-form-item label="登陆名称" prop="sname">
          <el-input v-model="loginForm.sname"></el-input>
        </el-form-item>
        <el-form-item label="登陆密码" prop="spassword">
          <el-input type="password" v-model="loginForm.spassword"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="grid-content bg-purple">
                <el-input type="text" v-model="loginForm.code"></el-input>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="grid-content bg-purple">
                <img :src="code" width="120px" height="40px"/>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-row style="position: relative; left: -45px">
          <el-button type="primary" @click="submitForm('loginForm')" class="loginUser">登 陆</el-button>
          <el-button type="primary" @click="addShops">注 册</el-button>
          <el-button type="success" @click="userLogin">切换用户登入</el-button>
        </el-row>
      </el-form>
    </div>

    <!-- 添加用户的模态框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="sbuinessForm" :rules="rules" ref="sbuinessForm" label-width="120px">
        <el-form-item label="商家名称" prop="sname">
          <el-input v-model="sbuinessForm.sname" autocomplete="off" @input="selectName"></el-input>
          <span v-if="msg" class="error-message">{{ msg }}</span>
        </el-form-item>
        <el-form-item label="商家密码" :label-width="formLabelWidth" prop="spassword">
          <el-input type="password" v-model="sbuinessForm.spassword" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商家电话" :label-width="formLabelWidth" prop="siphone">
          <el-input v-model="sbuinessForm.siphone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商家头像" :label-width="formLabelWidth">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:9092/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="sbuinessForm.src" :src="sbuinessForm.src" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSubmit">取 消</el-button>
        <el-button type="primary" :disabled="isConfirmButtonDisabled" @click="addShop">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import '@/css/UserAndAdmin.css';
import {setToken} from "@/utils/auth";
/*import Cookies from 'js-cookie'*/
export default {
  name: "merchantLogin",
  data() {
    return {
      loginForm: {
        sid: '',
        sname: 'lqz',
        spassword: '1',
        code: '',
        uuid: ''
      },
      sbuinessForm: { // 定义用户表单数据
        sid: '',
        sname: '',
        spassword: '',
        siphone: '',
        src: '',
        isUserNameAvailable: true, // 用于控制用户名是否可用
      },
      isConfirmButtonDisabled: true, // 初始状态禁用“确定”按钮
      msg: '', // 用于显示错误信息的变量
      rules: {
        sname: [
          {required: true, message: '请输入用户名称', trigger: 'blur'},
          {validator: this.checkNameAvailability, trigger: 'blur'}
        ],
        spassword: [
          {required: true, message: '请输入用户密码', trigger: 'blur'},
          {min: 1, max: 9, message: '长度在 1 到 9 个字符', trigger: 'blur'}
        ],
        siphone: [
          {required: true, message: '请输入用户电话', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'blur'}
        ],
        src: [
          {required: true, message: '请上传头像', trigger: 'blur'}
        ]
      },
      code: '', // 验证码图片的 src
      dialogFormVisible: false, // 控制模态框显示的变量
      title: '添加商家',
      formLabelWidth: '120px',
    };
  },
  methods: {
    // --------------------------------图片上传-------------
    handleAvatarSuccess(res) {
      this.sbuinessForm.src = res.data;
    },
    beforeAvatarUpload(file) {
      // 检查文件类型是否为 JPG, PNG 或 WebP
      const isJPGorPNGorWebP = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
      const isLt2M = file.size / 1024 / 1024 < 2; // 检查文件大小是否小于 2MB

      if (!isJPGorPNGorWebP) {
        this.$message.error('上传头像图片只能是 JPG, PNG 或 WebP 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPGorPNGorWebP && isLt2M;
    },
    // --------------------------------验证码-------------
    initCodeImage() {
      this.$axios.get('http://localhost:9092/captcha/getVerifyCodeImage')
          .then(response => {
            if (response.data.code === 200) {
              this.code = response.data.data;
              this.loginForm.uuid = response.data.uuid;
            }
          });
    },
    // --------------------------------商家登录-------------
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 如果验证通过，则发送数据到服务器
          this.login();
        } else {
          // 如果验证失败，则显示错误消息
          console.log('验证失败!');
          return false;
        }
      });
    },
    // 提交登入
    login() {
      this.$axios({
        url: 'http://localhost:9092/shops/login',
        method: 'POST',
        data: this.loginForm
      }).then(response => {
        if (response.data.code === 200) {
          console.log(response.data.data)
          // 登录成功，设置 cookie
          setToken(response.data.data)
          this.$message({
            type: 'success',
            message: response.data.msg
          });
          this.$router.push('/shopMain');
        } else {
          this.$message({
            type: 'error',
            message: response.data.msg
          });
        }
      }).catch(error => {
        console.error('请求失败:', error);
        this.$message.error('请求失败');
      });
    },

    userLogin() {
      this.$router.push('/userLogin');
    },

    // --------------------------------商家注册-------------
    reset() {
      this.sbuinessForm.sid = 0;
      this.sbuinessForm.sname = '';
      this.sbuinessForm.spassword = '';
      this.sbuinessForm.siphone = '';
      this.sbuinessForm.src = '';
    },
    addShops() {
      this.dialogFormVisible = true; // 显示模态框
    },
    addShop() {
      // 表单验证
      if (!this.sbuinessForm.sname || !this.sbuinessForm.spassword || !this.sbuinessForm.siphone || !this.sbuinessForm.src) {
        this.$message.error('请填写完整的用户信息');
        return;
      }
      this.$axios({
        url: "http://localhost:9092/shops/add",
        method: "post",
        data: this.sbuinessForm
      }).then((res) => {
        if (res.data.code == 200) {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          this.dialogFormVisible = false;
          this.reset();
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    cancelSubmit() {
      this.dialogFormVisible = false;
      this.resetUserForm();
      this.reset();
    },
    resetUserForm() {
      this.$refs.sbuinessForm.resetFields();
    },

    //   重名判断
    selectName() {
      if (this.sbuinessForm.sname.trim() === '') {
        this.msg = '商家名称不能为空';
        this.sbuinessForm.isUserNameAvailable = true; // 假设空名称不可用
        this.isConfirmButtonDisabled = true; // 禁用按钮
        return;
      }
      this.$axios({
        method: 'post',
        url: 'http://localhost:9092/shops/selectShopsName',
        data: {sname: this.sbuinessForm.sname}
      }).then((response) => {
        const data = response.data;
        if (data.code === 200) {
          this.msg = data.message;
          this.sbuinessForm.isUserNameAvailable = false;
          this.isConfirmButtonDisabled = true; // 禁用按钮
        } else {
          this.msg = "";
          this.sbuinessForm.isUserNameAvailable = true;
          this.isConfirmButtonDisabled = false; // 启用按钮
        }
      })
    },
    checkNameAvailability(rule, value, callback) {
      if (!this.sbuinessForm.isUserNameAvailable) {
        callback(new Error('该名字已存在，请重新输入'));
      } else {
        callback();
      }
    },
  },
  created() {
    this.initCodeImage();
  }
}
</script>

<style scoped>
.error-message {
  color: #a94442;
  font-size: 0.875em; /* 14px */
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-button {
  margin-left: 100px;
}

.loginUser {
  width: 120px;
}

.el-button + .el-button, .el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin-left: 5px;
}

.el-col-pull-0, .el-col-pull-1, .el-col-pull-10, .el-col-pull-11, .el-col-pull-12, .el-col-pull-13, .el-col-pull-14, .el-col-pull-15, .el-col-pull-16, .el-col-pull-17, .el-col-pull-18, .el-col-pull-19, .el-col-pull-2, .el-col-pull-20, .el-col-pull-21, .el-col-pull-22, .el-col-pull-23, .el-col-pull-24, .el-col-pull-3, .el-col-pull-4, .el-col-pull-5, .el-col-pull-6, .el-col-pull-7, .el-col-pull-8, .el-col-pull-9, .el-col-push-0, .el-col-push-1, .el-col-push-10, .el-col-push-11, .el-col-push-12, .el-col-push-13, .el-col-push-14, .el-col-push-15, .el-col-push-16, .el-col-push-17, .el-col-push-18, .el-col-push-19, .el-col-push-2, .el-col-push-20, .el-col-push-21, .el-col-push-22, .el-col-push-23, .el-col-push-24, .el-col-push-3, .el-col-push-4, .el-col-push-5, .el-col-push-6, .el-col-push-7, .el-col-push-8, .el-col-push-9, .el-row, .el-upload-dragger, .el-upload-list__item {
  position: relative;
  left: -10px;
}
</style>